package cn.sunxyz.data.orm.domain;

import cn.sunxyz.common.utils.StringUtil;
import cn.sunxyz.data.orm.impl.DefaultEntityQueryManger;
import cn.sunxyz.data.orm.EntityQueryManger;
import cn.sunxyz.data.orm.IMethod;
import cn.sunxyz.data.support.EntitySupport;

import java.util.List;

/**
 * Created by yangrd on 2017/6/7.
 */
public class SimpleDataBase<T, ID> implements CrudDatabase<T, ID> {

    private static EntityQueryManger entityQueryManger = DefaultEntityQueryManger.getSingleton();

    private final Class<T> entityCls;

    private final Class<T> idCls;

    public SimpleDataBase(Class<T> entityCls, Class<T> idCls) {
        this.entityCls = entityCls;
        this.idCls = idCls;
    }

    @Override
    public T findOne(ID id) {
        return entityQueryManger.query(getIMethod("findBy" + getIdProp()), id);
    }

    //TODO 暂未实现
    @Override
    public int save(T t) {
        return entityQueryManger.update("", t);
    }

    @Override
    public int delete(ID id) {
        return entityQueryManger.delete(getIMethod("delete" + getIdProp()), id);
    }

    @Override
    public List<T> findAll() {
        return entityQueryManger.queryList(getIMethod("findBy"));
    }

    public IMethod getIMethod(String name) {
        return IMethod.Builder.of(name, null, null, entityCls);
    }

    private String getIdProp() {
        return StringUtil.firstToUpper(EntitySupport.getIdField(entityCls).getName());
    }
}
